<template>
  <view class="applicant-container">
    <!-- 申请人列表 -->
    <view class="applicant-list">
      <u-cell-group v-if="applicantList.length > 0">
        <u-cell
          v-for="(item, index) in applicantList"
          :key="index"
          :title="item.name"
          isLink
          @click="handleEdit(item)"
        >
          <template #right-icon>
            <view @click.stop="handleDelete(item.id)">
              <u-icon
                name="close-circle-fill"
                color="#f56c6c"
                size="20"
              ></u-icon>
            </view>
          </template>
        </u-cell>
      </u-cell-group>
      <up-empty v-else></up-empty>
    </view>

    <u-modal
      :show="show"
      title="添加申请人"
      show-cancel-button
      @confirm="handleAddApplicant"
    >
      <u-input v-model="applicantName" placeholder="请输入申请人名称"></u-input>
    </u-modal>

    <!-- 底部添加按钮 -->
    <view class="footer-btn">
      <u-button type="primary" icon="plus" shape="circle" @click="handleAdd">
        添加申请人
      </u-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { onShow } from "@dcloudio/uni-app";
import { ref } from "vue";
import {
  type ApplicantItemType,
  type CreateApplicantParams,
  getApplicantList,
  createApplicant,
  deleteApplicant,
} from "@/common/apis/applicant";

const show = ref<boolean>(false);

const applicantList = ref<ApplicantItemType[]>([]);

const applicantName = ref<string>("");

const handleAdd = () => {
  show.value = true;
};

const handleEdit = (item: ApplicantItemType) => {
  uni.navigateTo({
    url: `/pages/user/applicant/detail?id=${item.id}`,
  });
};

const handleDelete = (id: number) => {
  uni.showModal({
    title: "提示",
    content: "确定删除该申请人吗？",
    success: async (res) => {
      if (res.confirm) {
        await deleteApplicant(id);
        await fetchGetApplicantList();
        uni.showToast({ title: "删除成功" });
      }
    },
  });
};

async function fetchGetApplicantList() {
  const response = await getApplicantList();
  if (response) {
    applicantList.value = response;
  }
}

async function handleAddApplicant() {
  const result = await createApplicant({
    name: applicantName.value,
  } as CreateApplicantParams);
  if (result) {
    uni.showToast({ title: "添加成功" });
    await fetchGetApplicantList();
    applicantName.value = ""; // 清空输入框
    show.value = false; // 关闭模态框
  } else {
    uni.showToast({ title: "添加失败", icon: "none" });
  }
}

onShow(() => {
  fetchGetApplicantList();
});
</script>

<style lang="scss" scoped>
.applicant-container {
  padding-bottom: 120rpx;

  .applicant-list {
    margin: 20rpx;
    background-color: #fff;
    border-radius: 10rpx;
  }

  .footer-btn {
    position: fixed;
    bottom: calc(env(safe-area-inset-bottom) + 30rpx);
    left: 30rpx;
    right: 30rpx;
  }
}
</style>
